﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using BW.Mes.WinForms;

namespace BW.Mes.WinForms.BasicData
{
    public partial class UpdateSupplierForm : DevExpress.XtraEditors.XtraForm
    {
        private SupplierForm.SupplierModel _model;
        private readonly HttpClient _httpClient = new HttpClient();
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";
        
        public UpdateSupplierForm(SupplierForm.SupplierModel model)
        {
            InitializeComponent();
            _model = model;
            textEditCode.Text = model.SupplierCode;
            textEditName.Text = model.SupplierName;
            textEditAbbreviation.Text = model.Abbreviation;
            comboBoxEditSuppType.Text = model.SuppType;
            comboBoxEditSuppLeave.Text = model.SuppLeave;
            textEditPhone.Text = model.Phone;
            comboBoxEditSuppHangye.Text = model.SuppHangye;
            textEditAddress.Text = model.Address;
            textEditUSCC.Text = model.USCC;
            comboBoxEditStatus.Text = model.Status;
            memoEditMsg.Text = model.SupplierMsg;
            // 在构造函数或Load事件中添加textEditMsg.EditValueChanged事件，事件内统计字符数、限制50、更新labelControlCount。
            memoEditMsg.EditValueChanged += MemoEditMsg_EditValueChanged;
        }
        
        public UpdateSupplierForm()
        {
            InitializeComponent();
        }
        
        private async void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(textEditCode.Text))
                {
                    XtraMessageBox.Show("供应商编号不能为空！", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textEditCode.Focus();
                    return;
                }
                if (string.IsNullOrWhiteSpace(textEditName.Text))
                {
                    XtraMessageBox.Show("供应商名称不能为空！", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textEditName.Focus();
                    return;
                }
                // 在保存/确定按钮事件中添加如下校验：
                string phone = textEditPhone.Text.Trim();
                if (phone.Length != 11 || !System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{11}$"))
                {
                    XtraMessageBox.Show("电话必须为11位数字！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                var model = new
                {
                    Id = _model.Id,
                    SupplierCode = textEditCode.Text.Trim(),
                    SupplierName = textEditName.Text.Trim(),
                    Abbreviation = textEditAbbreviation.Text?.Trim(),
                    SuppType = comboBoxEditSuppType.Text?.Trim(),
                    SuppLeave = comboBoxEditSuppLeave.Text?.Trim(),
                    Phone = textEditPhone.Text?.Trim(),
                    SuppHangye = comboBoxEditSuppHangye.Text?.Trim(),
                    Address = textEditAddress.Text?.Trim(),
                    USCC = textEditUSCC.Text?.Trim(),
                    Status = comboBoxEditStatus.Text?.Trim(),
                    SupplierMsg = memoEditMsg.Text?.Trim(),
                    UpdatedAt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")
                };
                string jsonData = JsonConvert.SerializeObject(model);
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                var response = await _httpClient.PutAsync($"{_apiBaseUrl}/T2/Supplier/UpdateSupplier", content);
                var responseContent = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null && ( (apiResult.code != null && apiResult.code.ToString() == "200") || (apiResult.message != null && apiResult.message.Contains("成功")) ))
                        {
                            XtraMessageBox.Show("修改成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                        else
                        {
                            string errorMessage = apiResult?.message ?? "修改失败，未知错误";
                            XtraMessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    catch (JsonException)
                    {
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                }
                else
                {
                    string errorMessage = $"HTTP错误：{response.StatusCode}";
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null && !string.IsNullOrEmpty(apiResult.message))
                        {
                            errorMessage = apiResult.message;
                        }
                    }
                    catch { }
                    XtraMessageBox.Show($"修改失败：{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"修改过程中发生错误：{ex.Message}", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void UpdateSupplierForm_Load(object sender, EventArgs e)
        {
            // 在构造函数或Load事件中添加textEditMsg.EditValueChanged事件，事件内统计字符数、限制50、更新labelControlCount。
            memoEditMsg.EditValueChanged += MemoEditMsg_EditValueChanged;
        }

        private void MemoEditMsg_EditValueChanged(object sender, EventArgs e)
        {
            MemoEdit memoEdit = sender as MemoEdit;
            if (memoEdit != null)
            {
                string text = memoEdit.Text;
                if (text.Length > 50)
                {
                    memoEdit.Text = text.Substring(0, 50);
                }
                labelControlCount.Text = $"字符数: {memoEdit.Text.Length}/50";
            }
        }
    }
}